//
//  TableViewRefreshView.m
//  iOSDevelopSDK
//
//  Created by Hayder on 2018/9/28.
//  Copyright © 2018年 Hayder. All rights reserved.
//

#import "HHTableRefreshView.h"
#import "HHGlobalDefine.h"

@interface HHTableRefreshView()

@property (nonatomic, strong) NSMutableArray *refreshImages;

/**是否允许再一次加载*/
@property (nonatomic, assign) BOOL isLoadingDataAgain;

@end

@implementation HHTableRefreshView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.tableView];
    
        self.emptyView = [[HHEmptyView alloc] initWithFrame:self.bounds];
        self.emptyView.hidden = YES;
        self.emptyView.image = BundlePngImage(@"hh_no_data");
        [self addSubview:self.emptyView];
        self.emptyView.delegate = self;
        
        self.page = 1;
    }
    
    return self;
}


/***
 刷新部分
 */
/**
 添加头部视图刷新
 */
- (void)addHeaderRefresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self
                                                                     refreshingAction:@selector(loadData)];
    self.tableView.mj_header = header;
}

/**
 添加尾部视图刷新
 */
- (void)addFooterRefresh
{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadData
{
    self.page = 1;
    self.tableView.mj_footer.hidden = NO;
    [self.tableView.mj_footer setState:MJRefreshStateIdle];
}

- (void)addSearchBarWithPlaceHolder:(NSString *)placeHolder{
    self.allDatas = [NSMutableArray array];
    HHBaseSearchBar *searchBar = [[HHBaseSearchBar alloc] initWithFrame:CGRectMake(0, 0, HH_SCREEN_WIDTH, 60)];
    searchBar.delegate = self;
    searchBar.textField.placeholder = placeHolder;
    self.searchBar = searchBar;
}

- (void)loadMoreData
{
    self.page++;
}

- (void)beginRefreshing
{
    [self.tableView.mj_header beginRefreshing];
}

- (void)endRefreshing
{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
}

/**
 处理返回的数据
 */
- (void)handleData:(NSArray *)data isRefresh:(BOOL) isRefresh
{
    self.isLoadingDataAgain = NO;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (isRefresh) {
        
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:data];
        
        [self.tableView reloadData];
        
        if (data.count == 0) {
            
            self.emptyView.hidden = NO;
//            self.emptyView.image = [UIImage imageNamed:@"none"];
//            self.emptyView.descriptionText = self.emptyDescription?self.emptyDescription:@"亲，暂无相关内容";
            self.tableView.mj_footer.hidden = YES;
        }else
        {
            self.tableView.mj_footer.hidden = NO;
            self.emptyView.hidden = YES;
        }
        
    }else
    {
        if (data.count == 0) {
            
            self.tableView.mj_footer.hidden = YES;
            [self.tableView.mj_footer setState:MJRefreshStateNoMoreData];
            [self toastMessage:@"没有更多数据了"];
        }else
        {
            [self.dataSource addObjectsFromArray:data];
            [self.tableView reloadData];
        }
    }
}

- (void)handleRequestError
{
    self.isLoadingDataAgain = YES;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
    
    self.emptyView.hidden = NO;
//    self.emptyView.image = [UIImage imageNamed:@"none"];
//    self.emptyView.descriptionText = @"暂无数据";
    //失败后page--
    if (self.page>0) {
        self.page--;
    }
}

/**处理数据错误*/
- (void)handleErrorWithText:(NSString *)text
{
    self.isLoadingDataAgain = YES;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
    
    self.emptyView.hidden = NO;
//    self.emptyView.image = [UIImage imageNamed:@"nodata"];
//    self.emptyView.descriptionText = text?text:@"数据异常";
}
#pragma mark -------------emptyDelegate-------------------
- (void)emptyViewDidClickImage:(HHEmptyView *)emptyView
{
    if (self.isLoadingDataAgain) {
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark -------------tableViewDelegate-------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.searchBar;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.searchBar.height;
}

#pragma mark ---------------------delegate----------------------------
- (void)didClickSearchBtn:(NSString *)searchText
{
    if (searchText.length == 0) {
        [self.viewController.view toastMessage:@"请输入搜索关键字"];
        return;
    }
    
    [self.searchBar.textField resignFirstResponder];
    self.searchText = searchText;
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
    self.page = 1;
    
    [self handleSearchText];
    
    if ([self.delegate respondsToSelector:@selector(tableRefreshDidSearchWithText:)]) {
        [self.delegate tableRefreshDidSearchWithText:searchText];
    }
}

- (void)handleSearchText
{
    
}

- (void)seachBarDidEditing:(NSString *)searchText
{
    if (searchText.length == 0) {//删除搜索内容，显示原来的数据
        self.searchText = @"";
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:self.allDatas];
        [self.tableView reloadData];
    }
}


#pragma mark -------------setter, getter-------------------
- (void)setEmptyDescription:(NSString *)emptyDescription
{
    _emptyDescription = emptyDescription;
    
    self.emptyView.descriptionText = emptyDescription;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColor.blueColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = UIColor.whiteColor;
        UIView *footView = [[UIView alloc] init];
        footView.backgroundColor = UIColor.whiteColor;
        _tableView.tableFooterView = footView;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    
    return _tableView;
}

- (NSMutableArray *)refreshImages
{
    if (!_refreshImages) {
        
        _refreshImages = [NSMutableArray array];
        
        for (int i=0; i<12; i++) {

            NSString *imageName = [NSString stringWithFormat:@"loading_%d",i];
            UIImage *image = [UIImage imageNamed:imageName];
            [_refreshImages addObject:image];
        }
    }
    
    return _refreshImages;
}


- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}

/**
 重新刷新ui
 */
- (void)reloadData
{
    [self.tableView reloadData];
}

@end
